package photobox.utils

import grails.converters.JSON
import org.springframework.util.StringUtils

/**
 * Created with IntelliJ IDEA.
 * User: sxing
 * Date: 13-12-16
 * Time: 下午7:27
 *
 */
class ParamUtils {
    static parseSort(params, allowFields, defaultSort) {
        def sort = params.sidx
        def order = params.sord
        if (!sort) return defaultSort
        if (!(order in ['asc', 'desc'])) order = 'asc'
        if (allowFields instanceof List) {
            if (sort in allowFields) {
                return [order: order, sort: sort]
            }
        } else if (allowFields instanceof Map) {
            if (allowFields.containsKey(sort)) {
                return [sort: allowFields.get(sort), order: order]
            }
        }

        return defaultSort
    }
    static parseSearch(params, allowFields) {
        def search = [:] as Map
        for( f in allowFields) {
            if (params.containsKey(f) && !params.get(f).isEmpty()) {
                search.put(f, params.get(f))
            }
        }
        return search
    }
    static parsePage(params) {
        Integer rows = [params.rows?(params.rows as Integer):25, 25].min()
        rows = [rows, 1].max()
        Integer page = params.page?(params.page as Integer):1
        return [ pageSize: rows, offset: (page - 1) * rows, page: page ]
    }

    static parseFilter(params) {
        def search = [:]
        if (!params) return search
        def filter = JSON.parse(params)
        for(def r in filter?.rules) {
            search.put(r.field, [
                    op:  r.op,
                    data:  r.data.trim()
            ])
        }
        return search
    }

}
